﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.SessionState;
using Core.Library;
using Core.Models;
using DataObject;
using DataObject.Cache;
using DataObject.Members;
using DataObject.Photo;
using DataObject.QA;
using DataObject.Ref;
using DataObject.Upload;
using DataObject.Vote;
using Newtonsoft.Json;

namespace Event.Handlers
{
    /// <summary>
    /// Summary description for AuthenticationHandler
    /// </summary>
    public class AuthenticationHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            ResponseData responseData = new ResponseData();

            string email = string.Empty;
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                FormsIdentity ident = HttpContext.Current.User.Identity as FormsIdentity;
                if (ident != null && ident.Ticket != null)
                {
                    FormsAuthenticationTicket ticket1 = ident.Ticket;
                    string[] userData = ticket1.UserData.Split('|');
                    email = userData[1];
                }
            }
            else if (HttpContext.Current.Session[Const.AuthenticationSessionName] != null)
            {
                string[] userData = HttpContext.Current.Session[Const.AuthenticationSessionName].ToString().Split('|');
                email = userData[1];
            }
            else
            {
                responseData = new ResponseData
                {
                    Success = false,
                    Type = 1,
                    Message = "Bạn phải đăng nhập để thực hiện hành động này."
                };
            }

            if(!string.IsNullOrEmpty(email))
            {
                string command;
                if (context.Request.RequestType == "POST")
                {
                    if (context.Request["command"] != null)
                    {
                        command = context.Request["command"];
                    }
                    else
                    {
                        command = null;
                        responseData = new ResponseData
                        {
                            Success = false,
                            Message = "Không có hành động này."
                        };
                    }
                }
                else
                {
                    if (context.Request.QueryString["command"] != null)
                    {
                        command = context.Request.QueryString["command"];
                    }
                    else
                    {
                        command = null;
                        responseData = new ResponseData
                        {
                            Success = false,
                            Message = "Không có hành động này."
                        };
                    }
                }

                if (command != null)
                {
                    var member = MembersCache.Members_GetByEmail(email);
                    if (member == null) return;

                    switch (command.ToLower())
                    {
                        case "uploadavatar":
                            responseData = UploadAvatar(context, member);
                            break;
                        case "cropavatar":
                            responseData = CropAvatar(context, member);
                            break;
                        case "multiuploadimages":
                            responseData = MultiUploadImages(context, member);
                            break;
                        case "uploadconfirm":
                            responseData = UploadConfirm(context, member);
                            break;
                        case "loadphotos":
                            responseData = LoadPhotos(context, member);
                            break;
                        case "vote":
                            responseData = Vote(context, member);
                            break;
                        case "sendqa":
                            responseData = SendQA(context, member);
                            break;
                        default:
                            responseData = new ResponseData
                            {
                                Message = "Không có hành động này",
                                Success = false
                            };
                            break;
                    }
                }                
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(JsonConvert.SerializeObject(responseData, Formatting.Indented));
        }

        private ResponseData SendQA(HttpContext context, MembersObject member)
        {
            var responseData = new ResponseData();
            if (!QACache.SendQA_TimeExpire(member.Member_ID))
            {
                responseData.Success = false;
                responseData.Message = "Bạn vui lòng đợi 30 giây sau mỗi lần gửi câu hỏi!";
            }
            else if (context.Request[Utils.Email] != null && context.Request[Utils.Name] != null && context.Request[Utils.Content] != null)
            {
                var email = UnicodeUtility.RemoveHtmlTag(context.Request[Utils.Email]);
                var name = UnicodeUtility.RemoveHtmlTag(context.Request[Utils.Name]);
                var content = UnicodeUtility.RemoveHtmlTag(context.Request[Utils.Content]);

                var qa = new QAObject();
                qa = new QAObject();
                qa.QA_Text = content;
                qa.QA_IsFeature = false;
                qa.QA_IsHighlight = false;
                qa.QA_IsActive = false;
                qa.QA_Name = name; //member.Member_Name;
                qa.QA_Email = email; // member.Member_Email;
                qa.QA_ReplyTo = 0;
                int res = QAController.QA_Create(qa);
                if (res > 0)
                {
                    responseData.Success = true;
                    responseData.Message = "Câu hỏi của bạn đã được gửi đi, chúng tôi sẽ phản hồi trong thời gian sớm nhất!";
                }
            }
            else
            {
                responseData.Success = false;
                responseData.Message = "Thông tin không hợp lệ!";
            }
            return responseData;
        }

        private ResponseData Vote(HttpContext context, MembersObject from)
        {
            ResponseData responseData = new ResponseData();
            var domain = from.Member_Email.Split('@');
            if (!RefCache.Ref_GetLockVoteStatus())
            {
                responseData.Success = false;
                responseData.Message = "Cổng bình chọn đã đóng!";
            }
            else if (RefCache.Ref_GetStringEmailClone().Contains(domain[1]))
            {
                responseData.Success = false;
                responseData.Message = "Email của bạn đã bị khóa!";
            }
            else if (!string.IsNullOrWhiteSpace(context.Request["id"]))
            {
                var id = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["id"]));
                if (id > 0)
                {
                    var to = MembersCache.Members_GetByIdStore(id);
                    if (to != null)
                    {
                        var xForwardedFor = context.Request.ServerVariables["X-Forwarded-For"] != null ? context.Request.ServerVariables["X-Forwarded-For"].Trim() : String.Empty;
                        var httpXForwardedFor = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null ? context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Trim() : String.Empty;
                        var remoteAddr = context.Request.ServerVariables["REMOTE_ADDR"] != null ? context.Request.ServerVariables["REMOTE_ADDR"].Trim() : String.Empty;
                        var time = DateTime.Now;


                        // check da vote
                        var lstVoted = VoteCache.Vote_GetVoteLogByFromID(from.Member_ID);
                        if (lstVoted != null && lstVoted.Where(d => d.VoteLog_ToID == to.Member_ID).Count() > 0)
                        {
                            responseData.Success = false;
                            responseData.Message = "Bạn đã bình chọn cho bài dự thi này!";
                            return responseData;
                        }
                        else if (RefCache.Ref_GetLockCloneStatus())
                        {
                            if (to.Member_IsLockVote)
                            {
                                responseData.Success = false;
                                responseData.Message = "Bài dự thi này đã bị khóa bình chọn!";
                                return responseData;
                            }
                            else if (to.Member_IsClone)
                            {
                                switch (to.Member_CloneLevel)
                                {
                                    case (int)CloneLevel.Low:
                                        if ((!VoteCache.Vote_AntiCloneLowLevel(to.Member_ID, httpXForwardedFor)))
                                        {
                                            responseData.Success = false;
                                            responseData.Message = "Bạn đã vote quá nhiều cho bài dự thi này, xin hãy bình chọn vào thời điểm khác!";
                                            return responseData;
                                        }
                                        break;
                                    case (int)CloneLevel.Normal:
                                        if ((!VoteCache.Vote_AntiCloneNormalLevel(to.Member_ID, httpXForwardedFor)))
                                        {
                                            responseData.Success = false;
                                            responseData.Message = "Bạn đã vote quá nhiều cho bài dự thi này, xin hãy bình chọn vào thời điểm khác!";
                                            return responseData;
                                        }
                                        break;
                                    case (int)CloneLevel.High:
                                        if ((!VoteCache.Vote_AntiCloneHighLevel(to.Member_ID, httpXForwardedFor)))
                                        {
                                            responseData.Success = false;
                                            responseData.Message = "Bạn đã vote quá nhiều cho bài dự thi này, xin hãy bình chọn vào thời điểm khác!";
                                            return responseData;
                                        }
                                        break;
                                }
                            }
                            else if (!VoteCache.Vote_IPFloodVote(httpXForwardedFor) && !VoteCache.Vote_DelayIPFloodVote(httpXForwardedFor))
                            {
                                responseData.Success = false;
                                responseData.Message = "Bạn hãy đợi trong ít phút!";
                                return responseData;
                            }
                        }

                        var o = new VoteLogObject
                        {
                            VoteLog_FromID = from.Member_ID,
                            VoteLog_FromEmail = from.Member_Email,
                            VoteLog_FromName = from.Member_Name,
                            VoteLog_ToID = to.Member_ID,
                            VoteLog_ToEmail = to.Member_Email,
                            VoteLog_ToName = to.Member_Name,
                            VoteLog_Time = time,
                            VoteLog_XForwardedFor = xForwardedFor,
                            VoteLog_HttpForwardedFor = httpXForwardedFor,
                            VoteLog_RemoteAddr = remoteAddr,
                            VoteLog_Round = RefCache.Ref_GetCurrentRound()
                        };
                        VoteController.Vote_AddVoteLogToCache(o);

                        // gui sang redis 
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var json = js.Serialize(o);
                        var rd = new Redis.VoteCache();
                        rd.Enqueue(json);
                        // gui sang redis 
                        responseData.Success = true;
                        responseData.Message = "Bình chọn thành công!";
                    }
                }
            }
            else
            {
                responseData.Success = false;
                responseData.Message = "Bình chọn không hợp lệ!";
            }
            return responseData;
        }

        private ResponseData LoadPhotos(HttpContext context, MembersObject member)
        {
            var responseData = new ResponseData();
            var lstReponse = new List<ResponseData>();
            var dt = PhotoCache.Photos_GetByMemberID(member.Member_ID, RefCache.Ref_GetCurrentRound());
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var r = dt.Rows[i];
                var responseItem = new ResponseData
                                   {
                                       Data = r[Constants.Table_Photos.Photo_Url].ToString(),
                                       ExData = r[Constants.Table_Photos.Photo_Description].ToString(),
                                       ExSize = r[Constants.Table_Photos.Photo_Size].ToString(),
                                       Success = true
                                   };
                lstReponse.Add(responseItem);
            }
            responseData.Data = lstReponse;
            responseData.Total = lstReponse.Count;
            responseData.Success = true;
            return responseData;
        }

        private ResponseData UploadConfirm(HttpContext context, MembersObject member)
        {
            ResponseData responseData = new ResponseData();
            if (!RefCache.Ref_GetLockRegisterStatus() && member.Member_Status != (int)MemberStatus.IsPublished)
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng đăng ký";
            }
            else if (!RefCache.Ref_GetLockEditStatus())
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng sửa thông tin";

            }
            else if (!UploadCache.UploadConfirm_TimeExpire(member.Member_ID))
            {
                responseData.Success = false;
                responseData.Message = "Bạn vui lòng đợi 30 giây sau mỗi lần sửa bài dự thi!";
            }
            else
            {


                if (UnicodeUtility.IsFullName(context.Request["fullname"])
                    //&& !string.IsNullOrWhiteSpace(context.Request["email"])
                    && !string.IsNullOrWhiteSpace(context.Request["address"])
                    && !string.IsNullOrWhiteSpace(context.Request["phone"])
                    && !string.IsNullOrWhiteSpace(context.Request["day"])
                    && !string.IsNullOrWhiteSpace(context.Request["month"])
                    && !string.IsNullOrWhiteSpace(context.Request["year"])
                    && !string.IsNullOrWhiteSpace(context.Request["gender"])
                    && !string.IsNullOrWhiteSpace(context.Request["city"])
                    && !string.IsNullOrWhiteSpace(context.Request["useravatar"]))
                    //&& !string.IsNullOrWhiteSpace(context.Request["albumavatar"])
                    //&& !string.IsNullOrWhiteSpace(context.Request["title"]))
                {
                    var fullname = UnicodeUtility.RemoveHtmlTag(context.Request["fullname"]);
                    var email = UnicodeUtility.RemoveHtmlTag(context.Request["email"]);
                    var address = UnicodeUtility.RemoveHtmlTag(context.Request["address"]);
                    var phone = UnicodeUtility.RemoveHtmlTag(context.Request["phone"]);
                    var day = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["day"]));
                    var month = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["month"]));
                    var year = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["year"]));
                    var gender = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["gender"]));
                    var city = ConvertUtility.ConvertTo<int>(UnicodeUtility.RemoveHtmlTag(context.Request["city"]));
                    var userAvatar = UnicodeUtility.RemoveHtmlTag(context.Request["useravatar"]);
                    var albumAvatar = UnicodeUtility.RemoveHtmlTag(context.Request["albumavatar"]);
                    var title = UnicodeUtility.RemoveHtmlTag(context.Request["title"]);
                    var about = UnicodeUtility.RemoveHtmlTag(context.Request["about"]);
                    var desc = UnicodeUtility.RemoveHtmlTag(context.Request["desc"]);
                    var images = context.Request["images"];

                    member.Member_FullName = fullname.Trim();
                    member.Member_DisplayName = Utils.GetFirstName(fullname);
                    member.Member_ContactEmail = email;
                    member.Member_Address = address;
                    member.Member_Tel = phone;
                    member.Member_Birthday = new DateTime(year, month, day);
                    member.Member_Gender = gender;
                    member.Member_City = city;
                    member.Member_Avatar = userAvatar;
                    switch (member.Member_InRound)
                    {
                        case (int)MemberRound.Round2:
                            member.Member_AlbumTitle2 = title;
                            member.Member_AlbumDesc2 = desc;
                            member.Member_OriginalAvatar2 = albumAvatar;
                            break;
                        case (int)MemberRound.Round3:
                            member.Member_AlbumTitle3 = title;
                            member.Member_AlbumDesc3 = desc;
                            member.Member_OriginalAvatar3 = albumAvatar;
                            break;
                        default:
                            member.Member_AlbumTitle1 = title;
                            member.Member_AlbumDesc1 = desc;
                            member.Member_OriginalAvatar = albumAvatar;
                            break;

                    }
                    member.Member_About = about;

                    var currentRound = RefCache.Ref_GetCurrentRound();

                    if (member.Member_Status == (int)MemberStatus.IsNoRegister)
                    {
                        member.Member_Status = (int)MemberStatus.IsPublished;
                        member.Member_InRound = (int)MemberRound.Round1;
                        member.Member_RegisterDate = DateTime.Now;
                        // tu vote khi dang ky lan dau
                        // check da vote
                        var lstVoted = VoteCache.Vote_GetVoteLogByFromID(member.Member_ID);
                        if (lstVoted == null || lstVoted.Where(d => d.VoteLog_ToID == member.Member_ID).Count() == 0)
                        {
                            var xForwardedFor = context.Request.ServerVariables["X-Forwarded-For"] != null
                                                    ? context.Request.ServerVariables["X-Forwarded-For"].Trim()
                                                    : String.Empty;
                            var httpXForwardedFor = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                                                        ? context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Trim()
                                                        : String.Empty;
                            var remoteAddr = context.Request.ServerVariables["REMOTE_ADDR"] != null
                                                 ? context.Request.ServerVariables["REMOTE_ADDR"].Trim()
                                                 : String.Empty;
                            var time = DateTime.Now;
                            var res = new VoteLogObject
                                          {
                                              VoteLog_FromID = member.Member_ID,
                                              VoteLog_FromEmail = member.Member_Email,
                                              VoteLog_FromName = member.Member_Name,
                                              VoteLog_ToID = member.Member_ID,
                                              VoteLog_ToEmail = member.Member_Email,
                                              VoteLog_ToName = member.Member_Name,
                                              VoteLog_Time = time,
                                              VoteLog_XForwardedFor = xForwardedFor,
                                              VoteLog_HttpForwardedFor = httpXForwardedFor,
                                              VoteLog_RemoteAddr = remoteAddr,
                                              VoteLog_Round = currentRound
                                          };
                            VoteController.Vote_AddVoteLogToCache(res);
                            // gui sang redis 
                            var js = new JavaScriptSerializer();
                            var json = js.Serialize(res);
                            var rd = new Redis.VoteCache();
                            rd.Enqueue(json);
                            // gui sang redis 
                        }
                        // tu vote khi dang ky lan dau
                    }

                    MembersController.Members_UpdateFrontEnd(member);

                    var lstImage = new List<ImageModel>();
                    if (!string.IsNullOrWhiteSpace(images))
                        lstImage = JsonConvert.DeserializeObject<List<ImageModel>>(images);

                    // xoa het anh cu
                    PhotoController.Photos_DeleteByMemberId(member.Member_ID, currentRound);
                    // insert anh moi
                    foreach (var i in lstImage)
                    {
                        PhotoController.InsertPhotoRound(member.Member_ID, string.Empty, i.Desc, i.Size, i.Image,
                                                         currentRound);
                    }

                    if (RefCache.Ref_GetMemberBreakCacheStatus())
                    {
                        CacheController.RemoveCachePort(Constants.ManagerCacheGroup.User);
                        CacheController.RemoveCachePort(Constants.ManagerCacheGroup.Photo);
                        //CacheController.RemoveCachePort(Constants.ManagerCacheGroup.Data);
                    }
                    else
                    {
                        PhotoCache.Photo_RemoveCacheMember(member.Member_ID, currentRound);
                    }


                    responseData.Success = true;
                    responseData.ExData = UrlHelpers.MembersDetails(member.Member_ID, member.Member_Email,
                                                                    member.Member_InRound);
                    responseData.Message = "Bài dự thi của bạn sẽ được cập nhật trong ít phút nữa.";
                }
                else
                {
                    responseData.Success = false;
                    responseData.Message = "Cập nhật thất bại";
                }
            }
            return responseData;
        }

        private ResponseData MultiUploadImages(HttpContext context, MembersObject member)
        {
            var count = ConvertUtility.ConvertTo<int>(context.Request["count"]);
            ResponseData responseData = new ResponseData();
            if (!RefCache.Ref_GetLockRegisterStatus() && member.Member_Status != (int)MemberStatus.IsPublished)
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng đăng ký";
            }
            else if (!RefCache.Ref_GetLockEditStatus())
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng sửa thông tin";

            }
            else
            {
                var lstReponse = new List<ResponseData>();
                if (!UploadCache.UploadImage_TimeExpire(member.Member_ID))
                {
                    responseData.Success = false;
                    responseData.Message = "Bạn vui lòng đợi 30 giây sau mỗi lần tải ảnh";
                }
                else if (count > UploadUtils.ImagesUploadMaxItems)
                {
                    responseData.Success = false;
                    responseData.Message = String.Format("Bạn chỉ được upload tối đa {0} hình.",
                                                         UploadUtils.ImagesUploadMaxItems - 1);
                }
                else if (context.Request.Files.Count > 0)
                {
                    var total = count > 0
                                    ? ((context.Request.Files.Count > (UploadUtils.ImagesUploadMaxItems - count))
                                           ? (UploadUtils.ImagesUploadMaxItems - count)
                                           : context.Request.Files.Count)
                                    : ((context.Request.Files.Count > (UploadUtils.ImagesUploadMaxItems - 1))
                                           ? (UploadUtils.ImagesUploadMaxItems - 1)
                                           : context.Request.Files.Count);

                    for (int i = 0; i < total; i++)
                    {
                        var responseItem = Upload(context.Request.Files[i], member, UploadUtils.ImagesUploadMaxSize, minWidth: UploadUtils.ImageMinWidth);
                        lstReponse.Add(responseItem);
                    }

                    if (context.Request.Files.Count > (UploadUtils.ImagesUploadMaxItems - 1))
                    {
                        lstReponse.Add(new ResponseData
                                           {
                                               Success = false,
                                               Message =
                                                   String.Format("Bạn chỉ được upload tối đa {0} hình.",
                                                                 UploadUtils.ImagesUploadMaxItems)
                                           });
                    }

                    responseData.Success = true;
                    responseData.Message = "Upload thành công!";
                }
                else
                {
                    responseData.Success = false;
                    responseData.Message = "Bạn phải chọn một file để up ảnh!";
                }
                responseData.Data = lstReponse;
                responseData.Total = lstReponse.Count;
            }
            return responseData;
        }

        private ResponseData CropAvatar(HttpContext context, MembersObject member)
        {
            var responseData = new ResponseData();

            if (!RefCache.Ref_GetLockRegisterStatus() && member.Member_Status != (int)MemberStatus.IsPublished)
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng đăng ký";
            }
            else if (!RefCache.Ref_GetLockEditStatus())
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng sửa thông tin";

            }
            else
            {

                var img = context.Request[Utils.Image];
                var w = (int)ConvertUtility.ConvertTo<float>(context.Request[Utils.w]);
                var h = (int)ConvertUtility.ConvertTo<float>(context.Request[Utils.h]);
                var x = (int)ConvertUtility.ConvertTo<float>(context.Request[Utils.x]);
                var y = (int)ConvertUtility.ConvertTo<float>(context.Request[Utils.y]);
                try
                {
                    var cropImage = Crop(img, w, h, x, y);
                    using (var ms = new MemoryStream(cropImage, 0, cropImage.Length))
                    {
                        var path = UploadUtils.GenerateUserImagesFolder(member.Member_ID);
                        ms.Write(cropImage, 0, cropImage.Length);
                        ms.Seek(0, SeekOrigin.Begin);
                        var s = new StorageWrapper();
                        path = path + "crop_" + UploadUtils.CutImageName(img);
                        s.Upload(path.TrimStart('/'), ms, true);
                        responseData.Success = true;
                        responseData.Data = path;
                        responseData.Message = "Upload ảnh thành công!";
                    }
                }
                catch (Exception ex)
                {

                    responseData.Success = false;
                    responseData.Message = "Lỗi crop ảnh";
                }
            }
            return responseData;
        }

        private ResponseData UploadAvatar(HttpContext context, MembersObject member)
        {
            ResponseData responseData = new ResponseData();
            if ((!RefCache.Ref_GetLockRegisterStatus() && member.Member_Status != (int)MemberStatus.IsPublished))
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng đăng ký";
            }
            else if (!RefCache.Ref_GetLockEditStatus())
            {
                responseData.Success = false;
                responseData.Message = "Đã đóng cổng sửa thông tin";

            }
            else if (!UploadCache.UploadImage_TimeExpire(member.Member_ID))
            {
                responseData.Success = false;
                responseData.Message = "Bạn vui lòng đợi 10 giây sau mỗi lần tải ảnh";
            }
            else if (context.Request.Files.Count > 0)
            {
                responseData = Upload(context.Request.Files[0], member, UploadUtils.AvatarUploadMaxSize,
                                      UploadUtils.AvatarMaxWidth, UploadUtils.AvatarMaxHeight, true, 
                                      UploadUtils.AvatarThumbWith, minWidth: UploadUtils.AvatarMinWidth, minHeight:UploadUtils.AvatarMinHeight);
            }
            return responseData;
        }

        private ResponseData Upload(HttpPostedFile file, MembersObject member, long uploadMaxSize = 0, int maxWidth = 0, int maxHeight = 0, bool isThumb = false, int width = 0, int minWidth = 0, int minHeight = 0)
        {
            var responseData = new ResponseData();
            if (JpegHelper.HasJpegExtension(file.FileName))
            {
                if (uploadMaxSize == 0 || file.ContentLength <= uploadMaxSize)
                {
                    try
                    {
                        var extention = Path.GetExtension(file.FileName);
                        var path = UploadUtils.GenerateUserImagesFolder(member.Member_ID);
                        path = path + UploadUtils.GenerateUserImagesFileName(extention);

                        var bdata = new byte[file.ContentLength];
                        file.InputStream.Read(bdata, 0, bdata.Length);
                        var ms = new MemoryStream(bdata);
                        var iImage = Image.FromStream(ms);
                        if (maxWidth > 0 && iImage.Width > maxWidth)
                        {
                            responseData.Success = false;
                            responseData.Message = string.Format("Chiều rộng ảnh không quá {0} pixels!", maxWidth);
                            return responseData;
                        }
                        if (maxHeight > 0 && iImage.Height > maxHeight)
                        {
                            responseData.Success = false;
                            responseData.Message = string.Format("Chiều cao ảnh không quá {0} pixels!", maxHeight);
                            return responseData;
                        }
                        if (minWidth > 0 && iImage.Width < minWidth)
                        {
                            responseData.Success = false;
                            responseData.Message = string.Format("Chiều rộng ảnh không được nhỏ hơn {0} pixels!", minWidth);
                            return responseData;
                        }
                        if (minHeight > 0 && iImage.Height < minHeight)
                        {
                            responseData.Success = false;
                            responseData.Message = string.Format("Chiều cao ảnh không được nhỏ hơn {0} pixels!", minHeight);
                            return responseData;
                        }
                        var s = new StorageWrapper();
                        ms.Seek(0, SeekOrigin.Begin);
                        s.Upload(path.TrimStart('/'), ms, true);

                        if (isThumb && width > 0 && iImage.Width > width)
                            path = StorageWrapper.Thumb_W(width, path, false);

                        responseData.Success = true;
                        responseData.Data = path;
                        responseData.ExSize = iImage.Width + "x" + iImage.Height;
                        responseData.Message = "Upload ảnh thành công!";
                    }
                    catch (Exception ex)
                    {
                        responseData.Success = false;
                        responseData.Message = "Lỗi upload ảnh";
                    }
                }
                else
                {
                    responseData.Success = false;
                    responseData.Message = "Ảnh vượt quá dung lượng cho phép !";
                }
            }
            else
            {
                responseData.Success = false;
                responseData.Message = "Ảnh phải là định dạng jpg hoặc png!";
            }
            return responseData;
        }

        static byte[] Crop(string Img, int Width, int Height, int X, int Y)
        {
            try
            {
                using (var imageStream = new System.Net.WebClient().OpenRead(Img))
                {
                    using (var originalImage = Image.FromStream(imageStream))
                    {
                        using (var bmp = new Bitmap(Width, Height))
                        {
                            bmp.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);

                            using (var Graphic = Graphics.FromImage(bmp))
                            {
                                Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                                Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                Graphic.DrawImage(originalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height, GraphicsUnit.Pixel);
                                var ms = new MemoryStream();
                                bmp.Save(ms, originalImage.RawFormat);
                                return ms.GetBuffer();
                            }
                        }
                    }
                }
            }

            catch (Exception Ex)
            {
                throw (Ex);
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}